<?php

if ($commit)
{
   
   if ($FILTER->isValidInteger($REQUEST->getRequestLast()))
   {
      $node = $TREE->getNode($REQUEST->getRequestLast())->save($REQUEST->data('f'));
   } else
   {
      $requestPath = $REQUEST->getRequestPath();
      $node = $TREE->addNode($requestPath[($REQUEST->getRequestLength() - 1)], $REQUEST->data('f'));
   }
   
   if($node != FALSE)
   {

      $new_node['id'] = $node->id;
      $new_node['parent'] = ($node->parent ? $node->parent : 0);
      $new_node['folder'] = 1;
      
      $params = array();
      $params['exec']   = 'parent.frames[\'tree\'].UpdateNode';
      $params['result'] = json_encode($new_node);
      $params['text']   = $node->title;
      $params['varkey'] = 'saved';
      $params['menu']['editagain'] = '/admin/category/' . $node->id . '.html';
      $params['menu']['newcategory'] = $node->parent ? '/admin/category/' . $node->parent . '/new.html' : '/admin/category/0/new.html';
      $params['menu']['newsubcategory'] = '/admin/category/' . $node->id . '/new.html';
      $ErrorHandler->setSuccess($params);
   } else
   {
      $ErrorHandler->setError();
   }

   $layout = 'results.html';
} else
{

   $data = NULL;

   if ($REQUEST->getRequestLast() != 'new')
   {
      $data = $TREE->getNode($REQUEST->getRequestLast());
   } else
   {
      $requestPath = $REQUEST->getRequestPath();
      $data = $TREE->getEmptyNode($requestPath[($REQUEST->getRequestLength() - 1)]);
      $SMARTY->assign('under_category', ($FILTER->isValidInteger($requestPath[($REQUEST->getRequestLength() - 1)]) ? $requestPath[($REQUEST->getRequestLength() - 1)] : 0));
   }

   $SMARTY->assign_by_ref('DataObject', $data);

   $layout = 'category.html';
}


/* 
 *
 * CHECK TREE:
 *
 * SELECT id FROM meccano_tree WHERE lt >= rt;
 * SELECT COUNT(id), MIN(lt), MAX(rt) FROM meccano_tree;
 * SELECT id, MOD((rt - lt) / 2) AS rest FROM meccano_tree WHERE rest = 0;
 *
 */
